import { createRouter, createWebHistory, RouteRecordRaw } from "vue-router";
import store from "../store";
import axios from "axios";

// import HomeView from '../views/HomeView.vue'

const routes: Array<RouteRecordRaw> = [
  {
    path: "/",
    name: "home",
    component: () => import("../views/HomeIndex.vue"),
  },
  {
    path: "/login",
    name: "login",
    // route level code-splitting
    // this generates a separate chunk (about.[hash].js) for this route
    // which is lazy-loaded when the route is visited.
    component: () => import("../views/LoginIndex.vue"),
    meta: { redirectAlredyLogin: true },
  },
  {
    path: "/signup",
    name: "signup",
    component: () => import("../views/SignUp.vue"),
    meta: { redirectAlredyLogin: true },
  },
  {
    path: "/column/:id",
    name: "column",
    component: () => import("../views/ColumnDetail.vue"),
    meta: { requiredLogin: true },
  },
  {
    path: "/create",
    name: "create",
    component: () => import("../components/CreatePost.vue"),
    meta: { requiredLogin: true },
  },
  {
    path: "/post/:id",
    name: "post",
    component: () => import("../views/PostDetail.vue"),
  },
];

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes,
});

//通过路由原信息
// router.beforeEach((to, form, next) => {
//   console.log(to.meta);
//   if (to.meta.requiredLogin && !store.state.user.isLogin) {
//     next({ name: "login" });
//   } else if (to.meta.redirectAlredyLogin && store.state.user.isLogin) {
//     next("/");
//   } else {
//     next();
//   }
// });

router.beforeEach((to, form, next) => {
  const { user, token } = store.state
  const { redirectAlredyLogin, requiredLogin } = to.meta
  if(!user.isLogin) {
    //没有登录
    if(token) {
      axios.defaults.headers.common.Authorization = `Bearer ${token}`
      store
      .dispatch('fetchCurrentUser')
      .then(() => {
        if(redirectAlredyLogin) {
          next('/')
        }else {
          next()
        }
      })
      .catch((e) => {
        console.log(e);
        store.commit('logout')
        next('/login')     
      })
    }else {
      if(requiredLogin) {
        next('/login')
      }else{
        next()
      }
    }
  }else {
    //登录
    if(redirectAlredyLogin) {
      next('/')
    }else {
      next()
    }
  }
})
export default router
